/*
 * This program is free software: you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program. If
 * not, see <http://www.gnu.org/licenses/>.
 */

import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;


public class Main {

  private static final String BASE_URL = "http://git.oschina.net/zhishi/asm_for_all/blob/master/";
  private static final String FILE_PATH = "../../";

  public static void main(String[] args) throws Exception {
    walkFile(new File(FILE_PATH));
  }

  private static void walkFile(File path) throws Exception {
    if (path.isFile()) {
      if (path.getName().endsWith(".asm")) {
        parseFile(path);
      }
    } else {
      File[] files = path.listFiles();
      if (files != null) {
        for (File file : files) {
          walkFile(file);
        }
      }
    }
  }

  private static void parseFile(File file) throws Exception {
    List<String> lines = getLinesFromSourceFile(file);
    List<String> overviewComment = new ArrayList<>();
    boolean startComment = true;
    for(String line : lines) {
      if (startComment) {
        // TODO: does all comment start with ; ?
        if (line.startsWith(";")) {
          overviewComment.add(trimComment(line));
        } else {
          startComment = false;
        }
      }
    }

    System.out.println("[" + file.getName() + "](" + BASE_URL
        + file.getPath().substring(FILE_PATH.length()) + ")");
    if (overviewComment.size() > 0) {
      System.out.println(String.join("\n", overviewComment));
    }
    System.out.println();
  }

  private static String trimComment(String line) {
    return line.replaceFirst("^;", "").trim();
  }

  private static List<String> getLinesFromSourceFile(File file) throws Exception {
    final List<String> lines = new ArrayList<>();
    Files.lines(file.toPath()).forEach(new Consumer<String>() {

      @Override
      public void accept(String t) {
        lines.add(t);
      }

    });
    return lines;
  }
}
